package cn.springsoter.core.redis.serializer;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * 将redis key序列化为字符串
 *
 * <p>
 * spring cache中的简单基本类型直接使用 StringRedisSerializer 会有问题
 * </p>
 *
 * @author wxl
 */
public class RedisKeySerializer implements RedisSerializer<String> {
	private final Charset charset;

	public RedisKeySerializer() {
		this(StandardCharsets.UTF_8);
	}

	public RedisKeySerializer(Charset charset) {
		Objects.requireNonNull(charset, "Charset must not be null");
		this.charset = charset;
	}

	@Override
	public String deserialize(byte[] bytes) {
		// redis keys 会用到反序列化
		if (bytes == null) {
			return null;
		}
		return new String(bytes, charset);
	}

	@Override
	public byte[] serialize(String object) {
		Objects.requireNonNull(object, "redis key is null");
		return object.getBytes(this.charset);
	}

}
